package com.zx.idc.backend.gui.api.commom.factory.compression;

import org.apache.commons.io.output.ByteArrayOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

/**
 * Created by hasee on 2019/2/20.
 */
public class ZIPCompressionImpl implements Compression {
    private final static Logger LOG = LoggerFactory.getLogger(ZIPCompressionImpl.class);
    private static final int num = 1024;
    private static final String zipSuffix = "zip";

    @Override
    public byte[] enCmp(String str) {
        try (
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                ZipOutputStream zip = new ZipOutputStream(bos, StandardCharsets.UTF_8);
        ) {
            byte[] data = str.getBytes();
            ZipEntry entry = new ZipEntry(zipSuffix);
            entry.setSize(data.length);
            zip.putNextEntry(entry);
            zip.write(data);
            zip.closeEntry();
            return bos.toByteArray();
        } catch (Exception ex) {
            LOG.error("压缩失败:", ex);
            return null;
        }

    }

    @Override
    public String deCmp(byte[] str) {
        byte[] b = null;
        try (
                ByteArrayInputStream bis = new ByteArrayInputStream(str);
                ZipInputStream zip = new ZipInputStream(bis, StandardCharsets.UTF_8);
                ByteArrayOutputStream baos = new ByteArrayOutputStream()
        ) {
            while (zip.getNextEntry() != null) {
                byte[] buf = new byte[num];
                int num = -1;
                while ((num = zip.read(buf, 0, buf.length)) != -1) {
                    baos.write(buf, 0, num);
                }
                b = baos.toByteArray();
            }
            return new String(b, StandardCharsets.UTF_8);
        } catch (Exception ex) {
            LOG.error("解压失败:", ex);
            return null;
        }
    }
}
